package com.ssuu.ssuusnow.project.manage.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssuu.ssuusnow.config.exception.AppException;
import com.ssuu.ssuusnow.project.manage.user.entity.MyUserDetails;
import com.ssuu.ssuusnow.project.manage.user.entity.User;
import com.ssuu.ssuusnow.project.manage.user.mapper.UserMapper;
import com.ssuu.ssuusnow.project.manage.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssuu.ssuusnow.utils.json.JsonUtil;
import com.ssuu.ssuusnow.utils.jwt.JwtUtils;
import com.ssuu.ssuusnow.utils.security.SecurityUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author sun
 * @since 2023-06-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    UserDetailsService userDetailsService;
    @Resource
    UserMapper userMapper;

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public int UpdateToLogin(Long t,Integer num) {
        User u = new User();
        u.setId(t);
        u.setNumberoflogins(num + 1);
        u.setUpdateTime(LocalDateTime.now());
        return userMapper.updateById(u);
    }

    @Override
    public List<String> getUserPermission(Long id) {
        List<String> list = new ArrayList<>();
        return list;
    }

    @Override
    public String login(String username, String password) {
        try {
            MyUserDetails userDetails = (MyUserDetails) userDetailsService.loadUserByUsername(username);
            UpdateToLogin(userDetails.getUser().getId(),userDetails.getUser().getNumberoflogins());
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new AppException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new
                    UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            User u = SecurityUtils.LoginUsers();
            String token = JwtUtils.generateToken(u.getId(), JsonUtil.getJSON(u));
            return token;
        } catch (AuthenticationException e) {
            throw new AppException("登录失败");
        }
    }

    @Override
    public Object listTo(User t) {
        QueryWrapper<User> wrappers = new QueryWrapper<>();
        wrappers.and(wrapper->{
            wrapper.eq("isdel",false);
            wrapper.like("email", Objects.isNull(t.getEmail())?"":t.getEmail());
            wrapper.like("phonenumber",Objects.isNull(t.getPhonenumber())?"":t.getPhonenumber());
            wrapper.like("name",Objects.isNull(t.getName())?"":t.getName());
            wrapper.like("username",Objects.isNull(t.getUsername())?"":t.getUsername());
            if (!Objects.isNull(t.getSex())) {
                wrapper.eq("sex", t.getSex());
            }
            if (!Objects.isNull(t.getEnterpriseId())) {
                wrapper.eq("enterpriseId", t.getEnterpriseId());
            }
            if (!Objects.isNull(t.getOfficeId())) {
                wrapper.eq("officeId", t.getOfficeId());
            }
            if (!Objects.isNull(t.getDepartmentId())) {
                wrapper.eq("departmentId", t.getDepartmentId());
            }
//        wrapper.eq("status",Objects.isNull(t.getStatus())?"":t.getStatus());
        });

        Page<User> page = new Page<>(t.getCurrentPage(),t.getPageSize());
        Object userPage = t.getPageSize() > 0 && t.getCurrentPage() > 0 ? userMapper.selectPage(page, wrappers) : userMapper.selectList(wrappers);
        return userPage;
    }

    @Override
    public int AddTo(User t) {
        t.setPassword(passwordEncoder.encode(t.getPassword()));
        t.setCreateTime(LocalDateTime.now());
        t.setUpdateTime(LocalDateTime.now());
        User lou =  SecurityUtils.LoginUsers();
        t.setUpdateby(lou.getId());
        t.setEnterpriseId(lou.getEnterpriseId());
        return userMapper.insert(t);
    }

    @Override
    public int UpdateTo(User t) {
        t.setPassword(passwordEncoder.encode(t.getPassword()));
        t.setUpdateTime(LocalDateTime.now());
        User lou =  SecurityUtils.LoginUsers();
        t.setUpdateby(lou.getId());
        return userMapper.updateById(t);
    }

    @Override
    public int DelTo(Long t) {
        User u = new User();
        u.setId(t);
        u.setUpdateTime(LocalDateTime.now());
        u.setIsdel(true);
        User lou =  SecurityUtils.LoginUsers();
        u.setUpdateby(lou.getId());
        return userMapper.updateById(u);
    }

}
